<?php

namespace app\api\controller\wechat;

use app\common\controller\Api;
use fast\Http;
use fast\Random;
use app\common\model\User;
use app\common\library\Token;
use think\Config;
use think\Validate;
use think\Db;
use think\Cache;

use app\admin\model\Questions as QuestionsModel;
use app\admin\model\Practicepaper as PracticepaperModel;
use app\admin\model\Practiceanswers as PracticeanswersModel;
use app\admin\model\Collection as CollectionModel;
/**
 * 小程序 考试
 */
class Practice extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        $this-> QuestionsModel = new QuestionsModel;
    }

    /**
     * 获取课程列表
     *
     * @return void
     */
    public function getCourse()
    {
      $list = Db::name('course')-> field(['name' => 'text', 'id' => 'value', 'pid' => 'pid']) ->order('id','asc')->select();
        if(!$list){
            $this->error("没有课程");
            exit;
        }
      $this->success('',$list);
    }

    /**
     * 练习题
     *
     * @return void
     */
    public function getQuestions($courseid = 0)
    {
        $list = Db::name('questions') -> field(['id']) -> where('course_id',$courseid) -> select();
        if(!$list){
            $this->error("该课程没有题目");
            exit;
        }
        $this->success('',$list);
    }

    public function getquestionIndex($questionid = 0)
    {
        $info = Db::name('questions') -> where('id',$questionid) -> find();
        
        if(!$info){
            $this->error("该题目不存在");
            exit;
        }
        if($info['typedata'] == '4'){
                $answers = json_decode($info["answers"],true);
                $info["answersCount"] = count($answers);

        }
        $this->success('',$info);
    }

    public function Practicecheck()
    {
        $data = $this->request->param();
        $userid = $data['userid'];
        $userinfo = Db::name('user')->where('id',$userid)->find();
        if(!$userinfo){
            $this->error("用户不存在");
            exit;
        }
        $practicepaperModel = new PracticepaperModel;

        $result = $practicepaperModel->where(['user_id' => $userid,'status' => '0'])->order('id','desc')->find();

        if($result){
            $this->success("您还有未完成的练习，是否继续",$result['id']);
            exit;
        }
        else{
            $this->success("您没有未完成的练习","");
            exit;
        }
    }

    public function setPractice(){
        $data = $this->request->param();

        $userid = $data['userid'];
        $userinfo = Db::name('user')->where('id',$userid)->find();
        if(!$userinfo){
            $this->error("用户不存在");
            exit;
        }

        $courseid = $data['courseid'];
        $type = $data["type"];
        $difficulty = $data["difficulty"];
        $count = $data["count"];
        $where = [];
        $practicepaperdata = [
            'title' => '练习'.time(),
            'user_id' => $userid,
        ];
        if($courseid){
            $where['course_id'] = $courseid;
            $practicepaperdata['course_id'] = $courseid;
        }
        if($type){
            $where['typedata'] = $type;
        }
        if($difficulty){
            $where['diffdata'] = $difficulty;
            $practicepaperdata['diffdata'] = $difficulty;
        }
        
        
        $questionsModel = new QuestionsModel;
        $practicepaperModel = new PracticepaperModel;

        $questionslist = $questionsModel->where($where)->limit($count)->orderRaw('RAND()')->select();
        if(!$questionslist){
            $this->error("没有该类型的题目");
            exit;
        }

        $result = [
            'type1' => [],
            'type2' => [],
            'type3' => [],
            'type4' => [],
            'type5' => []
        ];
    
        foreach ($questionslist as $question) {
            // 确保 typedata 存在且是数字
            $type = 'type' . ($question['typedata'] ?? 1);
            
            // 如果类型不在预定义中，跳过或处理异常
            if (!array_key_exists($type, $result)) {
                continue;
            }
    
            // 添加到对应类型数组
            $result[$type][] = [
                'id' => $question['id'] ?? 0
                // 如果需要 grade 可以在这里添加，但根据要求不需要
            ];
        }
        $practicepaperdata['questions'] = json_encode($result);
        $practicepaperstatus = $practicepaperModel->save($practicepaperdata);

        if(!$practicepaperstatus){
            $this->error("生成练习失败");
            exit;
        }
        
        // $qsArr = [];
        // foreach ($result as $type => $question) {

        //     $ids = array_column($question, 'id');
            

        //     if($type == 'type4'){
        //         $qs = DB::name('questions')->whereIn('id', $ids)->field('id,title,optionjson,diffdata,answers')->select();
        //         foreach ($qs as &$value) {
        //             $answers = json_decode($value["answers"],true);
        //             $value["answersCount"] = count($answers);
        //             unset($value["answers"]);
        //         }
        //     }
        //     else{
        //         $qs = DB::name('questions')->whereIn('id', $ids)->field('id,title,optionjson,diffdata,answers as ranswer')->select();
        //     }

        //     $qsArr[$type] = $qs;
        // }
        
        $this->success('生成练习成功',$practicepaperModel->id);
    }

    public function getPractice($data = null){
        $data = $this->request->param();
        $userid = (Int)$data['userid'];
        $practiceid = (Int)$data['practiceid'];
        $userinfo = Db::name('user')->where('id',$userid)->find();
        if(!$userinfo){
            $this->error("用户不存在");
            exit;
        }
        
        $practicepaperModel = new PracticepaperModel;

        $result = $practicepaperModel->where(['user_id'=>$userid,'id'=>$practiceid])->find();
        $result = json_decode($result['questions']);

        if(!$result){
            $this->error("没有练习");
            exit; 
        }
        
        $qsArr = [];
        foreach ($result as $type => $question) {

            $ids = array_column($question, 'id');
            

            if($type == 'type4'){
                $qs = DB::name('questions')->whereIn('id', $ids)->field('id,title,optionjson,diffdata,answerscontent,answers')->select();
                foreach ($qs as &$value) {
                    $answers = json_decode($value["answers"],true);
                    $value["answersCount"] = count($answers);
                    unset($value["answers"]);
                }
            }
            else{
                $qs = DB::name('questions')->whereIn('id', $ids)->field('id,title,optionjson,diffdata,answerscontent,answers as ranswer')->select();
                foreach ($qs as &$value) {
                    $value["ranswer"] = json_decode($value["ranswer"],true);

                }
            }

            $qsArr[$type] = $qs;
        }

        $this->success('获取练习成功',$qsArr);
    }

    public function submitPractice(){

        $rules = [
            'pra_id' => 'require',
            'answers' => 'require',
        ];
        $validate = new Validate($rules);
        if (!$validate->check(input('post.'))) {
            $this->error($validate->getError());
        }
        $pra_id = input('pra_id');
        $answers = input('answers/a');

        if (!Db::name('practicepaper')->where('id', $pra_id)->find()) {
            $this->error('练习不存在');
        }

        Db::startTrans();

        $result = false;
        
        $prapaperStatus = Db::name('practicepaper') -> where('id',$pra_id) -> update(['status'=>1]);
        if(!$prapaperStatus){
            $this->error("练习状态更改失败");
            exit;
        }

        $questions = Db::name('practicepaper')->where('id', $pra_id)->value('questions');
        $questions = json_decode($questions, true);
        
        $saveAnswerDatas = [];

        foreach ($questions as $type => $question) {
            if(!empty($question)){

                $ids = array_column($question,'id');
                $rightAnswers = Db::name('questions')->whereIn('id',$ids)->column('answers','id');

                
                foreach ($question as $k => $q) {
                    $id = $q["id"];

                    $saveAnswerArr = [
                        "pra_id"=>$pra_id,
                        "question_id"=>$id,
                        "answer_right"=>$rightAnswers[$id],
                        "answer_mine"=>"",
                        "grade"=>'0',
                    ];

                    if(isset($answers[$id]) && !empty($answers[$id])){
                        $saveAnswerArr["answer_mine"] = json_encode($answers[$id],JSON_UNESCAPED_UNICODE);
                        // 问答题
                        if($type != 'type5'){
                            if($answers[$id] == json_decode($rightAnswers[$id],true)){
                                // 回答正确
                                $saveAnswerArr["grade"] = '1';
                            }
                        }
                    }

                    $saveAnswerDatas[] = $saveAnswerArr;
                    
                }
            }
        }
        

        $answersStatus =  Db::name('practiceanswers')->insertAll($saveAnswerDatas);

        if(!$answersStatus){
            Db::rollback();
            $this->error("答案存储失败");
            exit;
        }
        
        $result = true;

        Db::commit();
        $this -> success("练习提交成功");
    }

    public function getWrong(){
        $data = $this->request->param();
        $userid = $data['userid'];
        $practiceanswersModel = new PracticeanswersModel;
        $idlist = $practiceanswersModel->name('practiceanswers') ->with('practicepaper') -> field(['question_id','COUNT(*) as count'])
         -> where(['grade'=>0,"user_id"=>$userid]) -> group('question_id') -> select();

        if(!$idlist){
            $this->error("没有错题");
            exit;
        }
        $datalist = [];
        foreach ($idlist as &$value) {
            $question = Db::name('questions')->where('id',$value["question_id"])->find();
            $question['count'] = $value["count"];
            $datalist[] = $question;
        }
        $this->success('',$datalist);
    }

    public function setCollection(){
        $data = $this->request->param();
        $userid = $data['userid'];
        $questionid = $data['questionid'];
        $del = $data['del']; //del:false表示不是删除，是添加收藏
        $collectionModel = new CollectionModel;
        if($del){
            $iscollection = $collectionModel -> where(['questions_id'=>$questionid,"user_id"=>$userid]) -> find();
            if(!$iscollection){
                $this->error("还未收藏过");
                exit; 
            }
            $collectionstatus = $collectionModel -> where(['questions_id'=>$questionid,"user_id"=>$userid]) -> delete();
            if(!$collectionstatus){
                $this->error("取消收藏失败");
                exit;
            }
            $this->success('取消收藏成功');
            exit;
        }
        else{
            $iscollection = $collectionModel -> where(['questions_id'=>$questionid,"user_id"=>$userid]) -> find();
            if($iscollection){
                $this->error("已经收藏过了");
                exit; 
            }
            $collectionstatus = $collectionModel ->save(['user_id'=>$userid,'questions_id'=>$questionid]);
            if(!$collectionstatus){
                $this->error("收藏失败");
                exit;
            }
            $this->success('收藏成功');
        }
    }

    public function getCollection(){
        $data = $this->request->param();
        $userid = $data['userid'];
        $collectionModel = new CollectionModel;

        $idlist = $collectionModel ->with('questions') -> field(['questions_id'])
         -> where(["user_id"=>$userid]) -> group('questions_id') -> select();

        if(!$idlist){
            $this->error("没有错题");
            exit;
        }
        $datalist = [];
        foreach ($idlist as &$value) {
            $question = Db::name('questions')->where('id',$value["questions_id"])->find();
            $datalist[] = $question;
        }
        $this->success('',$datalist);
    }

    public function checkCollection(){
        $data = $this->request->param();
        $userid = $data['userid'];
        $questionid = $data['questionid'];
        $collectionModel = new CollectionModel;

        $iscollection = $collectionModel -> where(['questions_id'=>$questionid,"user_id"=>$userid]) -> find();
        if(!$iscollection){
            $iscollection = false;
        }
        else{
            $iscollection = true;
        }
        $this->success('数据返回成功',$iscollection);
    }
}
